package com.lordjoe.collectiveintelligence.svm;

import libsvm.*;

import java.util.*;

/**
 * com.lordjoe.collectiveintelligence.svm.SVMLibDataItem
 *
 * @author Steve Lewis
 * @date May 25, 2009
 */
public class SVMLibDataItem implements ISVMDataItem
{
    public static SVMLibDataItem[] EMPTY_ARRAY = {};
    public static Class THIS_CLASS = SVMLibDataItem.class;

    private double m_Classification;
    private double m_PredictedClassification;
    private final List<svm_node> m_Items = new ArrayList<svm_node>();
    public SVMLibDataItem( ) {

    }

    public SVMLibDataItem(String s) {
        this();
        String[] items = s.split(" ");
        m_Classification = Double.parseDouble(items[0]);
        for (int i = 1; i < items.length; i++) {
            String item = items[i];
            m_Items.add(buildSVNNode(item));
        }
    }

    public double getPredictedClassification()
    {
        return m_PredictedClassification;
    }

    public void setPredictedClassification(double pPredictedClassification)
    {
        m_PredictedClassification = pPredictedClassification;
    }

    public static svm_node buildSVNNode(String s) {
        String[] items = s.split(":");
        svm_node ret = new svm_node();
        ret.index = Integer.parseInt(items[0]);
        ret.value = Double.parseDouble(items[1]);
        return ret;
    }
    public static String nodeToString(svm_node s) {
        StringBuilder sb = new StringBuilder();
        sb.append(s.index);
        sb.append(":");
        sb.append(s.value);
        return sb.toString();
    }


    public double getClassification()
    {
        return m_Classification;
    }

    public svm_node[] getNodes()
    {
        return m_Items.toArray(new svm_node[0]);
    }


    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        int classif = (int)getClassification();

        sb.append(Integer.toString(classif));
        svm_node[] svm_nodes = getNodes();
        for (int i = 0; i < svm_nodes.length; i++) {
            svm_node node = svm_nodes[i];
            sb.append(" ");
            sb.append(nodeToString(node));
        }
        return sb.toString();

    }
}
